package com.lv.leyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lv.leyou.dto.CategoryDTO;
import com.lv.leyou.entity.Category;
import com.lv.leyou.entity.CategoryBrand;
import com.lv.leyou.mapper.CategoryMapper;
import com.lv.leyou.service.CategoryBrandService;
import com.lv.leyou.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;
    @Override
    public Category queryGategoryById(Long id) {

        return getById(id);
    }

    @Override
    public List<Category> querylistByIds(List<Long> ids) {

        return listByIds(ids);
    }

    @Override
    public List<Category> queryGategoryByParentid(Long pid) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",pid);
        List<Category> categoryList = list(queryWrapper);
        return categoryList;
    }

    @Override
    public List<CategoryDTO> queryGategroupByBandId(Long brandId) {
        //根据品牌id，查询中间表，得到中间表对象集合
        List<CategoryBrand> categoryBrandList = this.categoryBrandService.query().eq("brand_id", brandId).list();
        if (CollectionUtils.isEmpty(categoryBrandList)) {
            return Collections.emptyList();
        }
        //获取分类id集合
        List<Long> categoryIdList = categoryBrandList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());
        //根据分类id集合，查询分类对象集合
        List<Category> categories = this.listByIds(categoryIdList);
        //转换DTO
        return CategoryDTO.convertEntityList(categories);
    }


}
